<template>
  <div class="header-wrap">
    <div class="content">
      <div class="logo">
        知乎
      </div>
      <div class="tab">
        <a-tabs v-model="defaultActiveKey" @change="changeTab">
          <a-tab-pane v-for="(item,index) in tabs" :key=index :tab=item>
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="serach">
        <a-input v-model="serachInput" placeholder="输入关键字" />
      </div>
      <a-button @click="openQuestion" class="btn" type="primary">
        提问
      </a-button>
<!--      提问的弹框-->
      <a-modal
          title="请输入你的问题"
          v-model="isQuestionVisible"
          @ok="handleOk" 
          @cancel="handleCancel"
      >
        <a-input style="margin-bottom:20px" placeholder="请输入标题" v-model="questionTitle"/>
        <a-textarea v-model="questionContent" placeholder="请输入你的问题" :auto-size="{ minRows: 5 }" />
        <div style="margin-top:20px" class="areas-wrap">
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="选择所属的领域"
            v-model="chooseAreas"
          >
            <a-select-option v-for="item in areas" :key="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </div>
      </a-modal>
      <div class="op_wrap">
        <div class="item marginR20 message">
          <a-popover overlayClassName="message-popover" v-model="isMessageVisible" trigger="click">
            <div slot="title">
              <a-tabs default-active-key="1" @change="clickMessageTabs">
                <a-tab-pane key="1">
                  <span slot="tab">
                    <a-icon type="apple" />
                  </span>
                </a-tab-pane>
                <a-tab-pane key="2">
                  <span slot="tab">
                    <a-icon type="fire" />
                  </span>
                </a-tab-pane>
                <a-tab-pane key="3">
                  <span slot="tab">
                    <a-icon type="heart" />
                  </span>
                </a-tab-pane>
              </a-tabs>
            </div>
<!--            <div @click="hideMessage" slot="content">-->
<!--            </div>-->
            <div class="icon-text">
              <div class="icon">
                <a-icon type="bell" />
              </div>
              消息
            </div>
          </a-popover>
        </div>
        <div class="item marginR20 private-message">
          <a-popover v-model="isPrivateMessageVisible" trigger="click">
            <div slot="title">
              <span>我的私信</span>
            </div>
            <div @click="hidePrivateMessage" slot="content">
              <p>Content</p>
              <p>Content</p>
            </div>
            <div class="icon-text">
              <div class="icon">
                <a-icon type="message" />
              </div>
              私信
            </div>
          </a-popover>
        </div>
        <div @click="toCreator" class="item people">
          <div class="icon">
            <a-icon type="user" />
          </div>
          创作中心
        </div>
      </div>
      <template v-if="isLogin">
        <a-popover v-model="isShowOptions" placement="bottom" trigger="click">
        <a slot="content">
          <div class="my-profile" @click="toProfile">
            我的主页
          </div>
          <div class="setting" @click="toSetting">
            设置
          </div>
          <div @click="handleLogOut">
            退出登录
          </div>
        </a>
        <div class="avatar small-hand">
          <img src="../assets/img.jpg" alt="">
        </div>
        </a-popover>
      </template>
      <a-button v-if="!isLogin" class="login-and-register-btn" @click="$router.push('/login')">登录/注册</a-button>
    </div>
    
    <!-- 完善个人信息 -->
    <a-modal v-model="isShowRegister" title="完善个人信息" :footer="null">
      <div class="register-wrap">
        <a-form-model
            ref="registerForm"
            :model="registerForm"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
        >
          <a-form-model-item labelAlign="left"  label="头像" prop="imageUrl" class="complete-info-wrap">
            <a-upload
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                :customRequest="doFileUpload"
                @change="handleChange"  
            >
              <img id="my-avatar" v-if="registerForm.imageUrl" :src="registerForm.imageUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item labelAlign="left" label="昵称" prop="name">
            <a-input
                v-model="registerForm.name"
            />
          </a-form-model-item>
          <a-form-model-item labelAlign="left" label="性别" prop="sex">
            <a-radio-group v-model="registerForm.sex">
              <a-radio value="1">
                男
              </a-radio>
              <a-radio value="2">
                女
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item labelAlign="left" label="简介" prop="info">
            <a-input v-model="registerForm.info" type="textarea" />
          </a-form-model-item>
          <a-form-model-item labelAlign="left" label="学校" prop="school">
            <a-select v-model="registerForm.school" placeholder="选择你的学校">
              <a-select-option value="shanghai">
                Zone one
              </a-select-option>
              <a-select-option value="beijing">
                Zone two
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item labelAlign="left" label="擅长的领域" prop="goodAreas">
            <a-select v-model="registerForm.goodAreas" placeholder="请选择你擅长的领域">
              <a-select-option value="shanghai">
                Zone one
              </a-select-option>
              <a-select-option value="beijing">
                Zone two
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ }">
            <div class="flex-center">
              <a-button type="primary" @click="onSubmit">
                完成
              </a-button>
              <a-button style="margin-left: 50px;" @click="resetForm">
                取消
              </a-button>
            </div>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {getUserInfo,uploadSingleImg,updateUserInfo,getAreas,publish} from "@/api/request";
import {getCurrentTime} from '@/assets/js/getTime'
import { bus } from '@/assets/js/bus.js';
export default {
  name: 'myHeader',
  components: {

  },
  data(){
    return{
      chooseAreas:[],
      questionTitle:'',
      areas:[],
      tabs:['首页','知学堂','商城','发现','等你来答'],
      isMessageVisible:false,
      isPrivateMessageVisible:false,
      defaultActiveKey:0,
      isQuestionVisible:false,
      questionContent:'',
      isShowOptions:false,
      isShowLoginAndRegister: true,
      
      registerForm:{
        imageUrl:undefined,
        name:undefined,
        sex:undefined,
        info:undefined,
        school:undefined,
        goodAreas:undefined
      },
      rules:{
        imageUrl:[{
          required: true, message: '请上传头像', trigger: ['change', 'blur']
        }],
        name:[{
          required: true, message: '请填入昵称', trigger: ['change', 'blur']
        }],
        sex:[{
          required: true, message: '请选择性别', trigger: ['change', 'blur']
        }],
        info:[{
          required: true, message: '请输入简介', trigger: ['change', 'blur']
        }],
        school:[{
          required: true, message: '请选择学校', trigger: ['change', 'blur']
        }],
        goodAreas:[{
          required: true, message: '请选择领域', trigger: ['change', 'blur']
        }],
      }
      ,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      loading: false,
      isShowRegister:false,
      isLogin:false,
      serachInput:''
    }
  },
  methods:{
    handleLogOut(){
      this.isLogin=false
      localStorage.setItem('userInfo','')
      localStorage.setItem('isLogin','')
      localStorage.setItem('token','')
      this.$router.push('/login')
    },
    //缓存变化的处理,只能监听其他页面的修改
    // handleStorageChange(event) {
    //   console.log('缓存变化',event)
    //   if (event.key === 'isLogin') {
    //     this.isLogin = JSON.parse(event.newValue);
    //   }
    // },
    changeTab(key){
      if(key==0){
        this.$router.push('/')
      }else if(key==1){
        this.$router.push('/education/learning')
      }else if(key==2){
        this.$router.push('/vip')
      }else if(key==3){
        this.$router.push('/explore')
      }
      else if(key==4){
        this.$router.push('/question/waiting')
      }
    },
    hideMessage(){
      this.isMessageVisible=false
    },
    hidePrivateMessage(){
      this.isPrivateMessageVisible=false
    },
    clickMessageTabs(key){
      console.log(key)
    },
    toCreator(){
      this.$router.push('/creator')
    },
    handleOk(){
      let obj={
        content:this.questionContent,
        time:getCurrentTime(),
        type:'3',
        title:this.questionTitle,
        areas:JSON.stringify(this.chooseAreas)
      }
      publish(obj).then(res=>{
        // console.log(res)
        if(res.data.status===0){
          this.$message.success('发布成功！')
          this.handleCancel()
        }
        else{
          this.$message.error('发布失败！')
        }
      })
    },
    handleCancel(){
      this.questionTitle=''
      this.questionContent=''
      this.isQuestionVisible=false
      this.chooseAreas=[]
    },
    openQuestion(){
      this.isQuestionVisible=true
    },
    toProfile(){
      this.$router.push('/profile')
      this.isShowOptions=false
    },
    toSetting(){
      // console.log('dd')
      this.isShowOptions=false
    },
    
    //完善信息的表单
    onSubmit() {
      console.log('hahah')
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          // alert('submit!');
          const { imageUrl, ...newRegisterForm } = this.registerForm;
          const updatedRegisterForm = {
            ...newRegisterForm,
            avatar: this.registerForm.imageUrl
          };
          console.log(updatedRegisterForm,'updatedRegisterForm')
          updateUserInfo(updatedRegisterForm).then(res=>{
            console.log(res,'aaa')
            if(res.data.status===0){
              this.isShowRegister=false
              //获取个人信息进行展示
              getUserInfo().then(res=>{
                if(res.data.status===0){
                  localStorage.setItem('userInfo',JSON.stringify(res.data.data))
                }
              }) 
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.registerForm.resetFields();
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
    handleChange(info) {
      // console.log(info,'aaaaa')
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.loading = false
      }
    },
    doFileUpload(file){
      // console.log(file,'file')
      let formData = new FormData();
      formData.append("file", file.file);
      uploadSingleImg(formData).then(res=>{
        // console.log(res)
        if(res.data.status===0){
          this.registerForm.imageUrl='http://localhost:3007/uploads/'+res.data.url
          this.loading = false;
          this.$message.success('上传成功！')
          //需要手动触发验证
          this.$refs.registerForm.validateField('imageUrl',(err)=>{
            if(err!==''){
              this.$message.error(err)
            }
          })
        }else {
          this.$message.error('上传失败！')
        }
      })
    },
    handleGetAreas(){
      getAreas().then(res=>{
        if(res.data.status===0){
          this.areas=res.data.data
        }
      })
    },
    handleSuccessLoginAndRegister(data){
      // 0表示登录成功，1表示注册成功，-1表示都失败
      if(data===0){
        //获取个人信息进行展示
        getUserInfo().then(res=>{
          if(res.data.status===0){
            localStorage.setItem('userInfo',JSON.stringify(res.data.data))
            localStorage.setItem('isLogin',JSON.stringify(true))
            this.isLogin=true
          }
        })
      }
      else if(data===1){
        this.isShowRegister=true
        localStorage.setItem('isLogin',JSON.stringify(true))
        this.isLogin=true
      }
      
    }
  },
  watch:{
    isShowRegister(newValue,oldValue){
      if(newValue!==oldValue){
        this.registerForm={
          imageUrl:'',
          name:'',
          sex:'',
          info:'',
          school:'',
          goodAreas:''
        }
      }
    }
  },
  mounted() {

    bus.$on('successLoginAndRegister', this.handleSuccessLoginAndRegister);

    if(localStorage.getItem('isLogin')!==''){
      const temp= JSON.parse( localStorage.getItem('isLogin') )
      this.isLogin = temp
      // this.isShowLoginAndRegister = !temp
      if(!temp){
        this.$router.push('/login')
      }
    }


  
    //监听缓存变化
    // window.addEventListener('storage', this.handleStorageChange);

    let newValue=this.$route
    if(newValue.path==='/'){
      this.defaultActiveKey=0
    }else if(newValue.path==='/education/learning'){
      this.defaultActiveKey=1
    }else if(newValue.path==='/vip'){
      this.defaultActiveKey=2
    }else if(newValue.path==='/explore'){
      this.defaultActiveKey=3
    }else if(newValue.path==='/question/waiting'){
      this.defaultActiveKey=4
    }
    this.handleGetAreas()
  },
  beforeUnmount() {
    // window.removeEventListener('storage', this.handleStorageChange);
  },
}
</script>

<style lang="less" scoped>
.header-wrap{
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}
.register-info{
  margin-top: 10px;
  width: 100%;
  .info{
    text-align: right;
    font-size:12px;
    color: #8590a6;
    cursor: pointer;
  }
}
.login-and-register-wrap{
  padding: 20px;
  .left{
    border-radius: 20px;
    overflow: hidden;
  }
  .right{
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    /deep/ .ant-form-item:last-of-type{
      margin-bottom: 0!important;
    }
  }
}
.login-and-register-btn{
  margin-left: 20px;
  background-color: #056de8;
  color: white;
}
.header-wrap{
  display: flex;
  justify-content: center;
  align-items: center;
  //box-shadow: 1px 3px gray;
  position: sticky;
  top: 0;
  background-color: #ffffff;
  z-index:99;
  .content{
    max-width: 1227px;
    display: flex;
    justify-content: center;
    align-items: center;
    .logo{
      font-size: 30px;
      font-weight: 600;
      color: #056de8;
      cursor: pointer;
    }
    .tab{
      margin: 0 25px;
      /deep/ .ant-tabs-bar{
        margin-bottom: 0;
      }
    }
    .btn{
      margin: 0 20px;
    }
    .op_wrap{
      display: flex;
      .message{
        /deep/ ant-popover-title{
          border-bottom: none!important;
        }
      }
      .item{
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 12px;
        cursor: pointer;
        .icon-text{
          display: flex;
          align-items: center;
          flex-direction: column;
        }
      }
    }
    .avatar{
      margin-left: 20px;
      width: 35px;
      height: 35px;
      border-radius: 5px;
      overflow: hidden;
    }
  }
}
.marginR20{
  margin-right: 20px;
}
</style>
<style lang="less">
.message-popover{
  .ant-popover-title{
    border-bottom: none;
  }
}
.complete-info-wrap{
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
}
</style>
